package com.ruoyi.integration.mqtt;

import com.ruoyi.integration.mqtt.config.MqttConfig;
import com.ruoyi.integration.mqtt.config.MqttProfile;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description :
 * @Author : Bruce Lee
 * @CreateTime : 2025/2/17
 */

@Component
public class MqttClientUtil {

    @Autowired
    private MqttProfile profile;

    @Autowired
    private MqttConfig mqttConfig;

    /**
     * 发布消息
     * @param topic
     * @param message
     * @throws Exception
     */
    public void publish(String topic, String message) throws Exception {
        MqttMessage mqttMessage = new MqttMessage();
        mqttMessage.setPayload(message.getBytes());
        mqttConfig.mqttClient.publish(topic, mqttMessage);
    }


    public void publish(String topic, String message, int qos) throws Exception {
        MqttMessage mqttMessage = new MqttMessage();
        mqttMessage.setPayload(message.getBytes());
        mqttMessage.setQos(qos);
        mqttConfig.mqttClient.publish(topic, mqttMessage);
    }
    /**
     * 订阅消息
     */
    public void subscribe(String topic) throws Exception {
        mqttConfig.mqttClient.subscribe(topic, profile.getQos());
    }


}
